<template>
  <a-card>
      <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
        <a-row type="flex" justify="start" :gutter="15">
          <a-col :md="5" :sm="24">
            <a-form-item>
              <a-input v-decorator="['email']" placeholder="Email" />
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item>
              <a-input v-decorator="['name']" :placeholder="$t('name')" />
            </a-form-item>
          </a-col>
          <a-col :md="14" :sm="24">
            <a-form-item>
              <a-space>
                <a-button htmlType="submit" type="primary" icon="search">{{$t('search')}}</a-button>
                <a-button type="primary" icon="plus" @click="showUserForm(0)">{{$t('add')}}{{$t('user')}}</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-table size="middle" :columns="columns" :data-source="data" :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'middle', showTotal:(total, range) => `${range[0]}-${range[1]} / ${total}`, current: pageIndex, pageSize: pageSize, total: total, pageSizeOptions:['10','20','30','50','100','1000','2000'], }" :row-key="record => record.userId" :loading="loading" @change="handleTableChange">
        <a-icon slot="status" slot-scope="text" :type="text == 1?'check-circle':'close-circle'" :style="text == 1?'color:#52c41a;font-size: 18px;':'font-size: 18px;'"/>
        <div slot="action" slot-scope="text, record">
          <a-space>
            <a-button @click="showUserForm(record.userId)">
              <a-icon type="edit"/>{{$t("edit")}}
            </a-button>
          </a-space>
        </div>
        <template v-for="(item, index) in columns" :slot="item.slotName">
          <span :key="index">{{ $t(item.slotName) }}</span>
        </template>
      </a-table>

      <a-modal v-model="editVisible" :maskClosable="false" :title="editTitle" :confirm-loading="confirmLoading" :okText="$t('submit')" @ok="saveUserForm()" @cancel="closeUserForm()">
        <a-form-model ref="userForm" layout="horizontal" :model="userForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 15 }" autocomplete="off" :rules="userFormRules">
          <a-input v-model="userForm.userId" type="hidden"/>
          <a-form-model-item label="Email" prop="userEmail" >
            <a-input v-model="userForm.userEmail" :readOnly="this.userForm.userId > 0" />
          </a-form-model-item>
          <a-form-model-item :label="$t('name')" prop="userName">
            <a-input v-model="userForm.userName" />
          </a-form-model-item>
          <a-form-model-item :label="$t('phone')" prop="userPhone">
            <a-input v-model="userForm.userPhone" />
          </a-form-model-item>
          <a-form-model-item :label="$t('password')" prop="userPwd">
            <a-input v-model="userForm.userPwd" />
          </a-form-model-item>
          <a-form-model-item :label="$t('status')" prop="userStatus">
            <a-switch v-model="userForm.userStatus" />
          </a-form-model-item>
          <a-form-model-item :label="$t('role')" prop="roles">
            <a-checkbox-group v-model="userForm.roles" :options="roleList">
            </a-checkbox-group>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
  </a-card>
</template>

<script>
import {getUserPageList, saveUser, getRoleList} from '@/services/user'

export default {
  name: "UserList",
  i18n: require('../i18n'),
  data () {
    return {
      data : [],
      columns:[
        {
          title: 'ID',
          dataIndex: 'userId',
          align:'center',
        },
        {
          title: 'Email',
          dataIndex: 'userEmail',
          sorter: (a, b) => a.userEmail.length - b.userEmail.length,
          align:'center',
        },
        {
          dataIndex: 'userName',
          sorter: (a, b) => a.userName.length - b.userName.length,
          align:'center',
          slotName: "name",
          slots: { title: 'name' },
        },
        {
          dataIndex: 'userPhone',
          align:'center',
          slotName: "phone",
          slots: { title: 'phone' },
        },
        {
          dataIndex: 'userStatus',
          align:'center',
          sorter: (a, b) => a.userStatus - b.userStatus,
          slotName: "status",
          slots: { title: 'status' },
          scopedSlots: { customRender: 'status' },
        },{
          align:'center',
          scopedSlots: { customRender: 'action' },
          slotName: "operation",
          slots: { title: 'operation' },
        }
      ],
      pageIndex: 1,
      pageSize: 10,
      total:0,
      loading: false,
      confirmLoading: false,
      searchParams: {},
      searchForm: this.$form.createForm(this, { name: 'search' }),
      editVisible: false,
      editTitle:"",
      userForm: {
        userId: 0,
        userEmail: "",
        userPwd: "",
        userName: "",
        userPhone: "",
        userStatus: true,
        roles:[],
      },
      userFormNull: {
        userId: 0,
        userEmail: "",
        userPwd: "",
        userName: "",
        userPhone: "",
        userStatus: true,
        roles:[],
      },
      userFormRules: {
        userEmail: [{ required: true, type: "email", message: ' ', trigger: 'blur' }],
        userName: [{ required: true, message: ' ', trigger: 'blur' }],
        userPhone: [{ required: true, message: ' ', trigger: 'blur' }],
      },
      roleList:[],
    }
  },
  methods: {
    handleSearch(e){
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
      });
      this.pageIndex = 1
      this.fetchData()
    },
    fetchData(){
      this.loading = true
      getUserPageList(this.pageIndex, this.pageSize, this.searchParams).then(res => {
        const {rows, total} = res.data.data
        this.data = rows
        this.total = total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleTableChange(pagination) {
      if(this.pageIndex === pagination.current && this.pageSize === pagination.pageSize)
        return

      this.pageIndex = pagination.current;
      this.pageSize = pagination.pageSize;
      this.fetchData()
    },
    showUserForm(userId){
      this.editVisible = true
      if(userId === 0) {
        this.editTitle = this.$t('add') + this.$t('user')
      }else{
        this.editTitle = this.$t('edit') + this.$t('user')
        const data = this.data.filter(item => item.userId === userId)[0]
        this.userForm = JSON.parse(JSON.stringify(data))
        const roles = []
        this.userForm.roles.forEach(role =>{
          roles.push(role.roleId)
        })
        this.userForm.roles = roles
        //console.log(this.userForm);
      }
    },
    closeUserForm(){
      this.confirmLoading = false
      this.editVisible = false
      this.userForm = JSON.parse(JSON.stringify(this.userFormNull))
      this.$refs.userForm.clearValidate()
    },
    saveUserForm(){
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          saveUser(this.userForm).then(res => {
            if(res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.closeUserForm()
              this.fetchData()
            }else{
              this.$message.error({content: this.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false;
        }
      });
    },
    getRoleList(){
      getRoleList().then(res => {
        const roles = res.data.data
        roles.forEach(role =>{
          this.roleList.push({label:role.roleName, value:role.roleId})
        })
      }).catch(error => {
        console.log(error)
      })
    },
  },
  created() {
    this.fetchData()
    this.getRoleList()
  }
}
</script>